<template>
  <div class="chat-history">
    <!-- 头部导航 -->
    <div class="header">
      <div class="header-left">
        <el-button @click="$router.push('/')" icon="ArrowLeft" circle />
        <h2>聊天历史</h2>
      </div>

      <div class="header-right">
        <el-button @click="clearAllHistory" type="danger" icon="Delete">
          清空历史
        </el-button>
      </div>
    </div>

    <!-- 内容区域 -->
    <div class="content">
      <div v-if="loading" class="loading">
        <el-skeleton :rows="5" animated />
      </div>

      <div v-else-if="error" class="error">
        <el-alert
          title="加载失败"
          :description="error"
          type="error"
          show-icon
          @close="loadSessions"
        />
      </div>

      <div v-else-if="sessions.length === 0" class="empty">
        <el-empty description="还没有聊天记录">
          <el-button type="primary" @click="$router.push('/')">
            开始聊天
          </el-button>
        </el-empty>
      </div>

      <div v-else class="sessions-list">
        <div
          v-for="session in sessions"
          :key="session.sessionId"
          class="session-item"
          @click="viewSession(session)"
        >
          <div class="session-avatar">
            <el-avatar :src="getAgentAvatar(session.agentId)" :size="50">
              <el-icon size="24"><Avatar /></el-icon>
            </el-avatar>
          </div>

          <div class="session-info">
            <h4 class="session-title">{{ session.title }}</h4>
            <p class="session-stats">
              {{ session.messageCount }} 条消息 • {{ formatTime(session.lastMessageTime) }}
            </p>
          </div>

          <div class="session-actions">
            <el-button
              type="primary"
              size="small"
              @click.stop="continueChat(session)"
            >
              继续对话
            </el-button>
            <el-button
              type="danger"
              size="small"
              icon="Delete"
              @click.stop="deleteSession(session)"
            />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { chatApi, agentApi } from '@/api'
import type { ChatSession, AiAgent } from '@/types'
import {useUserStore} from "@/stores/user.ts";

const router = useRouter()

// 响应式数据
const sessions = ref<ChatSession[]>([])
const agents = ref<Map<number, AiAgent>>(new Map())
const loading = ref(true)
const error = ref('')

const userStore= useUserStore();
// 生成用户ID（简化处理）
const userId = ref(userStore.userId)

// 组件挂载时加载数据
onMounted(async () => {
  await loadAgents()
  await loadSessions()
})

// 加载智能体信息
const loadAgents = async () => {
  try {
    const response = await agentApi.getEnabledAgents()
    if (response.code === 200) {
      response.data.forEach(agent => {
        agents.value.set(agent.id, agent)
      })
    }
  } catch (error) {
    console.error('加载智能体失败:', error)
  }
}

// 加载聊天会话列表
const loadSessions = async () => {
  try {
    loading.value = true
    error.value = ''

    const response = await chatApi.getUserSessions(userId.value)
    if (response.code === 200) {
      sessions.value = response.data
    } else {
      error.value = response.message || '获取聊天历史失败'
    }
  } catch (err) {
    error.value = '网络错误，请检查后端服务是否启动'
    console.error('加载聊天历史失败:', err)
  } finally {
    loading.value = false
  }
}

// 获取智能体头像
const getAgentAvatar = (agentId: number): string => {
  const agent = agents.value.get(agentId)
  return agent?.avatarUrl || ''
}

// 查看会话详情
const viewSession = (session: ChatSession) => {
  router.push(`/history/${session.sessionId}`)
}

// 继续对话
const continueChat = (session: ChatSession) => {
  router.push(`/chat/${session.agentId}?sessionId=${session.sessionId}`)
}

// 删除会话
const deleteSession = async (session: ChatSession) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除与"${session.title}"的对话记录吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    const response = await chatApi.deleteSession(session.sessionId)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      await loadSessions() // 重新加载列表
    } else {
      ElMessage.error(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除会话失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 清空所有历史记录
const clearAllHistory = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要清空所有聊天历史记录吗？此操作不可恢复。',
      '确认清空',
      {
        confirmButtonText: '清空',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    // 批量删除所有会话
    const promises = sessions.value.map(session =>
      chatApi.deleteSession(session.sessionId)
    )

    await Promise.all(promises)
    ElMessage.success('清空成功')
    await loadSessions()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('清空历史记录失败:', error)
      ElMessage.error('清空失败')
    }
  }
}

// 格式化时间
const formatTime = (timeString: string) => {
  const date = new Date(timeString)
  const now = new Date()
  const diffTime = now.getTime() - date.getTime()
  const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24))

  if (diffDays === 0) {
    return date.toLocaleTimeString('zh-CN', {
      hour: '2-digit',
      minute: '2-digit'
    })
  } else if (diffDays === 1) {
    return '昨天'
  } else if (diffDays < 7) {
    return `${diffDays}天前`
  } else {
    return date.toLocaleDateString('zh-CN')
  }
}
</script>

<style scoped>
.chat-history {
  min-height: 100vh;
  background: #f5f6fa;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background: white;
  border-bottom: 1px solid #e9ecef;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.header-left h2 {
  margin: 0;
  color: #2c3e50;
}

.content {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.loading, .error {
  background: white;
  border-radius: 12px;
  padding: 40px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.empty {
  background: white;
  border-radius: 12px;
  padding: 60px 40px;
  text-align: center;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

.sessions-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.session-item {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 20px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  border: 1px solid #f1f3f4;
  transition: all 0.3s ease;
  cursor: pointer;
}

.session-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border-color: #e3f2fd;
}

.session-info {
  flex: 1;
}

.session-title {
  margin: 0 0 8px 0;
  color: #2c3e50;
  font-size: 1.1rem;
  font-weight: 600;
}

.session-stats {
  margin: 0;
  color: #7f8c8d;
  font-size: 0.9rem;
}

.session-actions {
  display: flex;
  gap: 8px;
}

@media (max-width: 768px) {
  .header {
    padding: 16px;
  }

  .content {
    padding: 16px;
  }

  .session-item {
    padding: 16px;
  }

  .session-actions {
    flex-direction: column;
  }
}
</style>
